//
//  VideoDetailViewController.m
//  滴滴快拍
//
//  Created by dllo on 16/5/21.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "VideoDetailViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <Masonry/Masonry.h>
#import "ZFPlayer.h"
#import "Header.h"
#import "DMHeartFlyView.h"

#import "AppDelegate.h"
#import "FMDBTool.h"
#import "WeiboSDK+Statistics.h"
#import "StatisticsDemoRootViewController.h"
#import "DataBaseTool.h"

@interface VideoDetailViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) ZFPlayerView *playerView;
@property (nonatomic, strong) AGLVideo *videoModal;
@property (nonatomic, strong) BaseView *InforView;
@property (nonatomic, strong) BaseImageView *iconImage;
@property (nonatomic, strong) BaseLabel *nickLabel;
@property (nonatomic, strong) BaseLabel *finishTimeNiceLabel;
@property (nonatomic, strong) BaseLabel *vcntNiceLabel;
@property (nonatomic, strong) BaseLabel *tLabel;
@property (nonatomic, strong) BaseView *headView;

@property (nonatomic, strong) BaseTableView *commentTable;
@property (nonatomic, strong) NSMutableArray *commentArr;
@property (nonatomic, strong) AGLComment *comment;

@property (nonatomic, strong) BaseButton *shareButton;
@property (nonatomic, strong) BaseButton *likeButton;

/// 气球 大小
@property (nonatomic,assign) CGFloat heartSize;

/// 计时器
@property (nonatomic,strong) NSTimer *burstTimer;
@property (nonatomic, assign) BOOL isLike;

@property (nonatomic, assign) SelectDB isSave;


@end

@implementation VideoDetailViewController

- (void)dealloc
{
    //$(inherited) -ObjC -l"AFNetworking" -l"Masonry" -l"SDWebImage" -l"ZFPlayer" -framework "CoreGraphics" -framework "Foundation" -framework "ImageIO" -framework "MediaPlayer" -framework "MobileCoreServices" -framework "Security" -framework "SystemConfiguration" -framework "UIKit"
    // 找到 Build settings->Linking->Other Linker Flags 将此属性修改成-all_load  或者 -ObjC ，这个视情况而定。总之可以多试几次。
    NSLog(@"%@释放了",self.class);
    [self.playerView cancelAutoFadeOutControlBar];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    NSLog(@"http://api.miaopai.com/m/v2_channel.json?os=android&udid=0156a9d2-fb05-3001-83e2-e2592b043531&version=6.3.5&timestamp=1463663569521&unique_id=0156a9d2-fb05-3001-83e2-e2592b043531&per=1&token=FAvwTuEEUuHAV6JfgDvWYC-gGk6GSp0c&page=1&vend=miaopai&likeStat=1&uuid=0156a9d2-fb05-3001-83e2-e2592b043531&channel=huawei&fillType=255&deviceId=0156a9d2-fb05-3001-83e2-e2592b043531&scid=%@", self.scid);
    NSLog(@"%@", self.videoURL);
    
//    [[FMDBTool shareFMDBTool]openFavoriteDB];
//    [[FMDBTool shareFMDBTool] createFavoriteTable];
    

    [self createView];
    [self createData];


    self.heartSize = 36;

}

- (void)createView {
    [self createVideoView];
    [self createInformation];
    [self createTable];
    [self createButton];
}


#pragma mark 创建视频
- (void)createVideoView {
    
    // 监控当前屏幕是否竖屏,通过观察者进行监听屏幕状态
//    [self addNotification];

    
    //if use Masonry,Please open this annotation
    
     UIView *topView = [[UIView alloc] init];
     topView.backgroundColor = [UIColor blackColor];
    
     [self.view addSubview:topView];
     [topView mas_updateConstraints:^(MASConstraintMaker *make) {
     make.top.left.right.equalTo(self.view);
     make.height.mas_offset(20);
     }];
    
     self.playerView = [[ZFPlayerView alloc] init];
    //WithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_WIDTH /16 *9)
     [self.view addSubview:self.playerView];
     [self.playerView mas_makeConstraints:^(MASConstraintMaker *make) {
     make.top.equalTo(self.view).offset(20);
     make.left.right.equalTo(self.view);
//      注意此处，宽高比16：9优先级比1000低就行，在因为iPhone 4S宽高比不是16：9
     make.height.equalTo(self.playerView.mas_width).multipliedBy(9.0f/16.0f).with.priority(750);
     }];
    
    
    self.playerView.videoURL = self.videoURL;
    NSLog(@"%@", ZFCachesDirectory);
    // （可选设置）可以设置视频的填充模式，内部设置默认（ZFPlayerLayerGravityResizeAspect：等比例填充，直到一个维度到达区域边界）
    self.playerView.playerLayerGravity = ZFPlayerLayerGravityResizeAspect;
    // 打开断点下载功能（默认没有这个功能）
    self.playerView.hasDownload = YES;
    
    // 如果想从xx秒开始播放视频
    //self.playerView.seekTime = 15;
    __weak typeof(self) weakSelf = self;
    self.playerView.goBackBlock = ^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
}


- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    if (toInterfaceOrientation == UIInterfaceOrientationPortrait) {
        self.view.backgroundColor = [UIColor whiteColor];
        //if use Masonry,Please open this annotation
        ///*
         [self.playerView mas_updateConstraints:^(MASConstraintMaker *make) {
         make.top.equalTo(self.view).offset(20);
         }];
        
        [self.playerView mas_makeConstraints:^(MASConstraintMaker *make) {
            //      注意此处，宽高比16：9优先级比1000低就行，在因为iPhone 4S宽高比不是16：9
            make.height.equalTo(self.playerView.mas_width).multipliedBy(9.0f/16.0f).with.priority(750);
        }];
         //*/
        
        self.commentTable.hidden = NO;

    }else if (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight || toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
        self.view.backgroundColor = [UIColor blackColor];
        //if use Masonry,Please open this annotation
        ///*
         [self.playerView mas_updateConstraints:^(MASConstraintMaker *make) {
         make.top.equalTo(self.view).offset(0);
         }];
        
        [self.playerView mas_makeConstraints:^(MASConstraintMaker *make) {
            //      注意此处，宽高比16：9优先级比1000低就行，在因为iPhone 4S宽高比不是16：9
            make.height.equalTo(self.playerView.mas_width).multipliedBy(9.0f/16.0f).with.priority(750);
        }];
         //*/
        
        self.commentTable.hidden = YES;
    }
}

//#pragma mark 用来监听屏幕旋转的方法,监听播放器状态
//- (void)addNotification {
//    // 监听屏幕旋转
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(screenChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
//}
//#pragma mark 监听屏幕旋转触发的方法
//- (void)screenChange:(NSNotification *)notification {
//    // 通过状态栏找到当前屏幕旋转的方向
//    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
//    if (orientation == UIDeviceOrientationPortrait) {
//        NSLog(@"竖屏");
//        self.commentTable.hidden = NO;
//    }
//    
//}

#pragma mark 创建详情
- (void)createInformation {
    
    self.headView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 500)];
    
    self.iconImage = [[BaseImageView alloc] initWithFrame:CGRectMake(20, 20, ScreenWidth/6, ScreenWidth/6)];
    [self.headView addSubview:self.iconImage];
    self.iconImage.layer.cornerRadius = SCREEN_WIDTH /12;
    self.iconImage.layer.masksToBounds = YES;
    
    self.nickLabel = [[BaseLabel alloc] initWithFrame:CGRectMake(20 + self.iconImage.frame.size.width + 10, 20, ScreenWidth/4*3, ScreenWidth/12)];
    [self.headView addSubview:self.nickLabel];
    self.nickLabel.font = [UIFont systemFontOfSize:15];
    
    self.finishTimeNiceLabel = [[BaseLabel alloc] initWithFrame:CGRectMake(20 + self.iconImage.frame.size.width + 10, 20 + ScreenWidth/12, ScreenWidth/6, ScreenWidth/12)];
    [self.headView addSubview:self.finishTimeNiceLabel];
    self.finishTimeNiceLabel.font = [UIFont systemFontOfSize:12];
    self.finishTimeNiceLabel.textColor = [UIColor grayColor];
    
    self.vcntNiceLabel = [[BaseLabel alloc] initWithFrame:CGRectMake(self.finishTimeNiceLabel.frame.origin.x + self.finishTimeNiceLabel.frame.size.width + 20, 20 + ScreenWidth/12, ScreenWidth/3, ScreenWidth/12)];
    [self.headView addSubview:self.vcntNiceLabel];
    self.vcntNiceLabel.font = [UIFont systemFontOfSize:12];
    self.vcntNiceLabel.textColor = [UIColor grayColor];
    
    self.tLabel = [[BaseLabel alloc] initWithFrame:CGRectMake(20, self.iconImage.frame.origin.y + self.iconImage.frame.size.height + 20, ScreenWidth - 40, ScreenWidth / 6)];
    [self.headView addSubview:self.tLabel];
    
    // 创建手势
        UITapGestureRecognizer *tapGesture =
        [[UITapGestureRecognizer alloc] initWithTarget:self
                                                action:@selector(showTheLove)];
    
        // 给谁添加手势
        [self.headView addGestureRecognizer:tapGesture];
    // 长按手势
    UILongPressGestureRecognizer *longPressGesture =
    [[UILongPressGestureRecognizer alloc]
     initWithTarget:self
     action:@selector(longPressGesture:)];
    
    // 长按多久触发
    longPressGesture.minimumPressDuration = 0.2;
    
    // 给谁添加手势
    //    [self.view addGestureRecognizer:longPressGesture];
    [self.headView addGestureRecognizer:longPressGesture];
    

}

#pragma mark 创建Table
- (void)createTable {
    
    self.commentTable = [[BaseTableView alloc] initWithFrame:CGRectMake(0, SCREEN_WIDTH /16 *9 + 20, SCREEN_WIDTH, SCREEN_HEIGHT - 49 - (SCREEN_WIDTH /16 *9 + 20)) style:UITableViewStylePlain];
    [self.view addSubview:self.commentTable];
    
    self.commentTable.delegate = self;
    self.commentTable.dataSource = self;
    [self.commentTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];// tableView 取消下划线
    [self.commentTable registerClass:[VideoDetailTableCell class] forCellReuseIdentifier:NSStringFromClass([VideoDetailTableCell class])];
//    self.commentTable.tableHeaderView = self.headView;
}

#pragma mark Table协议方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.commentArr.count;
}

#pragma mark 设置分区头部标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *str = [NSString stringWithFormat:@"评论 %ld", self.commentArr.count];
    return str;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    AGLComment *comment = self.commentArr[indexPath.row];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15], NSFontAttributeName, nil];
    CGRect rect = [comment.content boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 40, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    return 20 + 20 + SCREEN_WIDTH/12 + rect.size.height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    VideoDetailTableCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([VideoDetailTableCell class]) forIndexPath:indexPath];
    AGLComment *comment = self.commentArr[indexPath.row];
    cell.comment = comment;
 
    return cell;
}


#pragma mark 创建收藏分享
- (void)createButton {
    self.shareButton = [BaseButton buttonWithType:UIButtonTypeSystem];
    [self.shareButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.shareButton.backgroundColor = [UIColor colorWithRed:85 / 255.0 green:122 / 255.0 blue:204 / 255.0 alpha:1];
    [self.shareButton setTitle:@"转发" forState:UIControlStateNormal];
    [self.shareButton addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    self.shareButton.frame = CGRectMake(0, SCREEN_HEIGHT -49, SCREEN_WIDTH /2, 49);
    [self.view addSubview:self.shareButton];
    
    self.likeButton = [BaseButton buttonWithType:UIButtonTypeSystem];
    [self.likeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.likeButton.backgroundColor = [UIColor colorWithRed:207 / 255.0 green:125 / 255.0 blue:158 / 255.0 alpha:1];
    [self.likeButton addTarget:self action:@selector(likeAction) forControlEvents:UIControlEventTouchUpInside];
    self.likeButton.frame = CGRectMake(SCREEN_WIDTH /2, SCREEN_HEIGHT -49, SCREEN_WIDTH /2, 49);
    [self.view addSubview:self.likeButton];
//    [self.likeButton setTitle:@"收藏" forState:UIControlStateNormal];
//    if (self.isLike == NO) {
//        [self.likeButton setTitle:@"收藏" forState:UIControlStateNormal];
//
//    }else {
//        [self.likeButton setTitle:@"已收藏" forState:UIControlStateNormal];
//        
//    }
    //判断是否收藏
    self.isSave = [[DataBaseTool shareDataBase] isExistInTable:self.scid];
    if (self.isSave == SelecInTable) {
        [self.likeButton setTitle:@"已收藏" forState:UIControlStateNormal];
        
    } else {
        [self.likeButton setTitle:@"收藏" forState:UIControlStateNormal];
    }

    
    
    // 长按手势
    UILongPressGestureRecognizer *longPressGesture =
    [[UILongPressGestureRecognizer alloc]
     initWithTarget:self
     action:@selector(longPressGesture:)];
    
    // 长按多久触发
    longPressGesture.minimumPressDuration = 0.2;
    
    // 给谁添加手势
//    [self.view addGestureRecognizer:longPressGesture];
    [self.likeButton addGestureRecognizer:longPressGesture];

    
}
- (void)shareAction:(UIButton *)button {
    NSLog(@"分享");
    AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    authRequest.redirectURI = @"https://api.weibo.com/oauth2/default.html";
    authRequest.scope = @"all";
    
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:[self messageToShare] authInfo:authRequest access_token:myDelegate.wbtoken];
    request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    //    request.shouldOpenWeiboAppInstallPageIfNotInstalled = NO;
    [WeiboSDK sendRequest:request];

}

- (WBMessageObject *)messageToShare
{
    WBMessageObject *message = [WBMessageObject message];
//    NSString *str = [NSString stringWithContentsOfURL:self.videoURL encoding:nil error:nil];
    
        message.text = NSLocalizedString(self.videoModal.streambase, nil);
    return message;
    }
    










- (void)likeAction {
    NSLog(@"收藏");
//    if (self.isLike == NO) {
//        [self.likeButton setTitle:@"已收藏" forState:UIControlStateNormal];
//        [[FMDBTool shareFMDBTool] insertLike:self.videoModal];
//
//    }else {
//        [self.likeButton setTitle:@"收藏" forState:UIControlStateNormal];
//        [[FMDBTool shareFMDBTool] deleteLike:self.videoModal];
//    }
//    _isLike = !_isLike;
    
    if (self.isSave == SelectNotInTable) {
        if ([[DataBaseTool shareDataBase] insertInTable:self.videoModal]) {
            [self.likeButton setTitle:@"已收藏" forState:UIControlStateNormal];
        }
        
    } else if (self.isSave == SelecInTable) {
        [[DataBaseTool shareDataBase] deleteFromTable:self.videoModal.scid];
        [self.likeButton setTitle:@"收藏" forState:UIControlStateNormal];
        
    }
    self.isSave = !self.isSave;


    [self showTheLove];
}

- (void)showTheLove {
    // 创建
    DMHeartFlyView *heart = [[DMHeartFlyView alloc]
                             initWithFrame:CGRectMake(0, 0, _heartSize, _heartSize)];
    
    // 添加
    [self.view addSubview:heart];
    
    
    //    CGPoint fountainSource =
    //    CGPointMake(20 + _heartSize * 0.5,
    //                self.view.bounds.size.height - _heartSize * 0.5 - 10);
    CGPoint fountainSource =
    CGPointMake(self.view.bounds.size.width - 20 - _heartSize * 0.5,
                self.view.bounds.size.height - _heartSize * 0.5 - 10);
    
    
    heart.center = fountainSource;
    
    // 开始动画
    [heart viewAnimate:self.view];
}

- (void)longPressGesture:(UILongPressGestureRecognizer *)longPressGesture {
    
    
    switch (longPressGesture.state) {
            
            // 手势开始了
        case UIGestureRecognizerStateBegan:
            
            // 计时器
            _burstTimer = [NSTimer scheduledTimerWithTimeInterval:0.2
                                                           target:self
                                                         selector:@selector(showTheLove)
                                                         userInfo:nil
                                                          repeats:true];
            
            break;
            
            // 手势结束了
        case UIGestureRecognizerStateEnded:
            
            // 残废计时器
            [_burstTimer invalidate];
            
            // 释放
            _burstTimer = nil;
            
            break;
            
        default:
            break;
    }
}


#pragma mark 请求数据 

- (void)createData {
    // 请求分类
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:[NSString stringWithFormat:@"http://api.miaopai.com/m/v2_channel.json?os=android&udid=0156a9d2-fb05-3001-83e2-e2592b043531&version=6.3.5&timestamp=1463663569521&unique_id=0156a9d2-fb05-3001-83e2-e2592b043531&per=1&token=FAvwTuEEUuHAV6JfgDvWYC-gGk6GSp0c&page=1&vend=miaopai&likeStat=1&uuid=0156a9d2-fb05-3001-83e2-e2592b043531&channel=huawei&fillType=255&deviceId=0156a9d2-fb05-3001-83e2-e2592b043531&scid=%@", self.scid] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //        [self saveData:responseObject DataName:@"hotMovieTable"];
        //        NSLog(@"%@", responseObject);
        NSDictionary *dic = responseObject;
        NSDictionary *result = dic[@"result"];
        self.videoModal = [[AGLVideo alloc] init];
        [self.videoModal setValuesForKeysWithDictionary:result];
//        self.playerView.videoURL = [NSURL URLWithString:self.videoModal.streambase];
        [self.iconImage setImageWithURL:[NSURL URLWithString:self.videoModal.icon] placeholderImage:[UIImage imageNamed:@"PlaceHolder"]];
        self.nickLabel.text = self.videoModal.nick;
        self.finishTimeNiceLabel.text = self.videoModal.finishTimeNice;
        self.vcntNiceLabel.text = [NSString stringWithFormat:@"%@ 观看",self.videoModal.vcntNice];
        
        self.tLabel.text = self.videoModal.t;
        self.tLabel.numberOfLines = 0;
        [self.tLabel sizeToFit];
        
        self.commentTable.frame = CGRectMake(0, SCREEN_WIDTH /16 *9 + 20, SCREEN_WIDTH, SCREEN_HEIGHT - 49 - (SCREEN_WIDTH /16 *9 + 20));
        self.headView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.tLabel.frame.origin.y + self.tLabel.frame.size.height + 20);
        self.commentTable.tableHeaderView = self.headView;
//        self.isLike = [[FMDBTool shareFMDBTool] columnFavoriteExists:self.videoModal.icon inTableWithName:@"like"];
        



        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"视频详情联网失败");
        //        NSDictionary *dic = [self getDataWithDataName:@"hotMovieTable"];
        //        if (dic == nil) {
        //            NSLog(@"请连网啊亲");
        //        } else {
        //            NSDictionary *data = dic[@"data"];
        //            NSArray *hot = data[@"hot"];
        //            self.movieArr = [AGLMovie baseModalByArr:hot];
        //            [self.tableView reloadData];
        //        }
        //        
        
    }];
    
    
    // 请求评论
    [manager GET:[NSString stringWithFormat:@"http://api.miaopai.com/m/v2_comment.json?timestamp=1463663569528&unique_id=0156a9d2-fb05-3001-83e2-e2592b043531&os=android&per=20&token=FAvwTuEEUuHAV6JfgDvWYC-gGk6GSp0c&page=1&vend=miaopai&udid=0156a9d2-fb05-3001-83e2-e2592b043531&uuid=0156a9d2-fb05-3001-83e2-e2592b043531&channel=huawei&deviceId=0156a9d2-fb05-3001-83e2-e2592b043531&version=6.3.5&scid=%@", self.scid] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //        [self saveData:responseObject DataName:@"hotMovieTable"];
        //        NSLog(@"%@", responseObject);
        NSDictionary *dic = responseObject;
        NSArray *result = dic[@"result"];
        self.commentArr = [AGLComment baseModalByArr:result];
        [self.commentTable reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"评论联网失败");
        //        NSDictionary *dic = [self getDataWithDataName:@"hotMovieTable"];
        //        if (dic == nil) {
        //            NSLog(@"请连网啊亲");
        //        } else {
        //            NSDictionary *data = dic[@"data"];
        //            NSArray *hot = data[@"hot"];
        //            self.movieArr = [AGLMovie baseModalByArr:hot];
        //            [self.tableView reloadData];
        //        }
        //
        
    }];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
